package com.lld.message.mq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lld.message.dto.ImMessageBodyEntity;
import com.lld.message.model.DoStoreGroupMessageDto;
import com.lld.message.model.DoStoreP2PMessageDto;
import com.lld.message.service.StoreMessageService;
import com.rabbitmq.client.Channel;
import org.lld.im.common.constant.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author: LunBoWang
 * @description: TODO
 * @date: 2025/4/5 下午8:11
 * @version: 1.0
 */
@Service
public class StroeGroupMessageReceiver {
    private static final Logger logger = LoggerFactory.getLogger(StroeGroupMessageReceiver.class);

    @Resource
    StoreMessageService storeMessageService;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = Constants.RabbitConstants.StoreGroupMessage, durable = "true"),
                    exchange = @Exchange(value = Constants.RabbitConstants.StoreGroupMessage, durable = "true")
            ), concurrency = "1"
    )
    public void onChatMessage(@Payload Message messsage,
                              @Headers Map<String, Object> headers,
                              Channel channel) throws Exception {
        String msg=new String(messsage.getBody(),"utf-8");
        logger.info("接收到消息：:::{}",msg);
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        try{
            JSONObject jsonObject = JSON.parseObject(msg);

            DoStoreGroupMessageDto doStoreGroupMessageDto = jsonObject.toJavaObject(DoStoreGroupMessageDto.class);

            ImMessageBodyEntity messageBody = jsonObject.getObject("messageBody", ImMessageBodyEntity.class);
            doStoreGroupMessageDto.setImMessageBodyEntity(messageBody);
            storeMessageService.doStoreGroupMessage(doStoreGroupMessageDto);
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            logger.error("处理消息出现异常：{}",e.getMessage());
            logger.error("RMQ_CHAT_TEAN_ERROR",e);
            logger.error("NACK_MSG:{}",msg);
            //第一个false表示不批量拒绝，第二个false表示不重回队列
            channel.basicNack(deliveryTag,false,false);
        }
    }
}
